<?php

namespace summer\swoole\pool;

use Swoole\Coroutine;
use Swoole\Coroutine\Channel as CoChannel;
use SplQueue;
use summer\swoole\pool\contract\ConnectionInterface;

class Channel
{
    protected $size;

    /**
     * @var CoChannel;
     */
    protected $channel;

    /**
     * @var SplQueue
     */
    protected $queue;

    public function __construct(int $size)
    {
        $this->size = $size;
        $this->channel = new CoChannel($size);
        $this->queue = new \SplQueue();
    }

    /**
     * @param float $timeout
     * @return ConnectionInterface|false
     */
    public function pop(float $timeout)
    {
        if ($this->isCoroutine()) {
            return $this->channel->pop($timeout);
        }
        return $this->queue->shift();
    }

    /**
     * @param ConnectionInterface $data
     * @return bool
     */
    public function push($data)
    {
        if ($this->isCoroutine()) {
            return $this->channel->push($data);
        }
        $this->queue->push($data);
        return true;
    }

    public function length(): int
    {
        if ($this->isCoroutine()) {
            return $this->channel->length();
        }
        return $this->queue->count();
    }

    public function isCoroutine(): bool
    {
        return Coroutine::getCid() > 0;
    }
}